package org.c41.graphics.effect;

import org.c41.util.Check;

public class Blink extends AlphaEffect {

	public static final int LOOP_CONTINUALLY = -1;
	
	private final long smooth;
	private final long during_time;
	private int loop_count = LOOP_CONTINUALLY;
	private long end_time;
	private long current_time;
	
	public Blink(Paintable base, long time){
		super(base);
		Check.greater(time, 0L);
		
		if(time<100L){
			time=100L;
		}
		this.during_time=time;
		if(this.during_time<=1000L){
			this.smooth=100L;
		}
		else {
			this.smooth=500L;
		}
	}
	
	public void setLoopCount(int count){
		this.loop_count=count;
		this.end_time=during_time*count;
	}
	
	public int getLoopCount(){
		return loop_count<=0?LOOP_CONTINUALLY:loop_count;
	}
	
	public int getAlredyLoopCount(){
		return (int) (current_time/during_time);
	}

	@Override
	protected float updateAlpha(long current) {
		current_time=current;
		if(loop_count>0&&current_time>=end_time){
			complete();
			return 1.0f;
		}
		long frames = this.during_time/smooth;
		long index= current_time%this.during_time/frames;
		if(index>smooth){
			index=smooth;
		}
		float alpha=2.0f/smooth*index;
		if(index>=smooth/2){
			alpha=2.0f-alpha;
		}
		alpha=1.0f-alpha;
		return alpha;
	}

}
